#include "timer3_led.h"
#include <stdint.h>
#include "led_driver.h"
#include "gd32f4xx_timer.h"

/**
 * 定时器3:通用定时器,
 * 4通道:
 * CH0:PB6,PD12 ;
 * CH1:PB7,PD13;
 * CH2 : PB8 , PD14 ;
 * CH3 : PB9 , PD15 ;
 */
void led_sw_on(void)
{
    gpio_mode_set(GPIOC, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, LED_SW);
    gpio_output_options_set(GPIOC, GPIO_OTYPE_PP, GPIO_OSPEED_2MHZ, LED_SW);
    gpio_bit_reset(GPIOC, LED_SW);
}

void timer3_led_config(void)
{
    // 设置引脚复用模式
    rcu_periph_clock_enable(RCU_GPIOD);

    gpio_mode_set(GPIOD, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN_12);
    gpio_mode_set(GPIOD, GPIO_MODE_AF, GPIO_PUPD_NONE, GPIO_PIN_13);

    // 定时器配置
    rcu_periph_clock_enable(RCU_TIMER3);
    rcu_timer_clock_prescaler_config(RCU_TIMER_PSC_MUL4); // 4倍频到168Mhz
    timer_deinit(TIMER3);                                 // 复位

    //
    timer_parameter_struct initpara;
    timer_struct_para_init(&initpara);
    // 分频
    initpara.prescaler = 10000;
    initpara.period = 168 - 1;
    timer_init(TIMER3, &initpara);

    // 通道
    timer_oc_parameter_struct ocpara;
    timer_channel_output_struct_para_init(&ocpara);

    // 极性
    ocpara.outputstate = TIMER_CCX_ENABLE;

    // 通道
    timer_channel_output_config(TIMER3, TIMER_CH_0, &ocpara);
    timer_channel_output_config(TIMER3, TIMER_CH_1, &ocpara);
    timer_channel_output_config(TIMER3, TIMER_CH_2, &ocpara);
    timer_channel_output_config(TIMER3, TIMER_CH_3, &ocpara);
    ///
    // 通道输出模式
    timer_channel_output_mode_config(TIMER3, TIMER_CH_0, TIMER_OC_MODE_PWM1);
    timer_channel_output_mode_config(TIMER3, TIMER_CH_1, TIMER_OC_MODE_PWM1);
    timer_channel_output_mode_config(TIMER3, TIMER_CH_2, TIMER_OC_MODE_PWM1);
    timer_channel_output_mode_config(TIMER3, TIMER_CH_3, TIMER_OC_MODE_PWM1);

    // ccr
    timer_channel_output_pulse_value_config(TIMER3, TIMER_CH_0, 0);
    timer_channel_output_pulse_value_config(TIMER3, TIMER_CH_1, 0);
    timer_channel_output_pulse_value_config(TIMER3, TIMER_CH_2, 0);
    timer_channel_output_pulse_value_config(TIMER3, TIMER_CH_3, 0);

    //
    timer_enable(TIMER3);
}

void timer_led_pwm_update(float duty, uint16_t ch)
{
    uint32_t ccr = (uint32_t)(duty * TIMER_PERIOD);
    timer_channel_output_pulse_value_config(TIMER3, ch, ccr);
}